using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms.CoreLab;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Data;
using ctsu.Shared;

namespace ctsu.Admin.BusLogic.CoreLab
{
	class BLFormSstChangeLocation : BLCoreLabFormBaseImpl
	{
		//private SelectLocationDlg _sld;
		private bool ignoreEvent = false;
		#region control references
		private GridControl _testSamples;
		private TextBox _id;
		private DateTimePickerAdv _batchDate;
		private TextBox _batchName;
		private TextBox _editType;
		private TextBox _note;
		private TextBox _disposition;
		private DateTimePickerAdv _outDate;

		private ComboBox _freezer;
		private NumericUpDown _shelf;
		private NumericUpDown _rack;
		private NumericUpDown _box;

		private Button _btnRetrieveItems;
		private Button _btnUpdateSelected;
		private Button _btnUpdateAll;
		private Button _btnClear;
		private Button _btnRemoveBatch;
		private Button _btnPrint;
		private Button _selectLocation;

		private CheckBox _chkIncludeComment;
		private CheckBox _chkIncludeDisposition;
		#endregion control references

		public BLFormSstChangeLocation(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{
		}

		#region initialize
		protected override void _vcManager_OnAfterHookEvents()
		{
			_testSamples = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			_id = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_batchDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("BatchDate", this._form.Controls);
			_outDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("OutDate", this._form.Controls);
			_batchName = (TextBox)Forms.Utils.GetControlByName("BatchName", this._form.Controls);
			_editType = (TextBox)Forms.Utils.GetControlByName("EditType", this._form.Controls);
			_note = (TextBox)Forms.Utils.GetControlByName("Note", this._form.Controls);
			_disposition = (TextBox)Forms.Utils.GetControlByName("Disposition", this._form.Controls);

			_btnRetrieveItems = (Button)Forms.Utils.GetControlByName("btnRetrieveItems", this._form.Controls);
			_btnUpdateSelected = (Button)Forms.Utils.GetControlByName("btnUpdateSelected", this._form.Controls);
			_btnUpdateAll = (Button)Forms.Utils.GetControlByName("btnUpdateAll", this._form.Controls);
			_btnClear = (Button)Forms.Utils.GetControlByName("btnClear", this._form.Controls);
			_btnRemoveBatch = (Button)Forms.Utils.GetControlByName("btnRemoveBatch", this._form.Controls);
			_selectLocation = (Button)Forms.Utils.GetControlByName("SelectLocation", this._form.Controls);

			_chkIncludeComment = (CheckBox)Forms.Utils.GetControlByName("chkIncludeComment", this._form.Controls);
			_chkIncludeDisposition = (CheckBox)Forms.Utils.GetControlByName("chkIncludeDisposition", this._form.Controls);

			_btnPrint = (Button)Forms.Utils.GetControlByName("btnPrint", this._form.Controls);
			_chkPrintSelected = (CheckBox)Forms.Utils.GetControlByName("chkPrintSelected", this._form.Controls);
			_chkPrintReport = (CheckBox)Forms.Utils.GetControlByName("chkPrintReport", this._form.Controls);

			_freezer = (ComboBox)Forms.Utils.GetControlByName("Freezer", this._form.Controls);
			_shelf = (NumericUpDown)Forms.Utils.GetControlByName("Shelf", this._form.Controls);
			_rack = (NumericUpDown)Forms.Utils.GetControlByName("Rack", this._form.Controls);
			_box = (NumericUpDown)Forms.Utils.GetControlByName("Box", this._form.Controls);
			this._form.btnRemove.Visible = false;
		}

		public override void InitializeEmptyControls()
		{
			_freezer.SelectedIndex = -1;
		}

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_btnClear.Enabled = enable;
			_btnRetrieveItems.Enabled = enable;

			if (enable == false)
			{
				_btnUpdateSelected.Enabled = enable; ;
				_btnUpdateAll.Enabled = enable;
				_btnRemoveBatch.Enabled = enable;
			}

			_freezer.Enabled = enable;
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			_shelf.Enabled = enable;
			_shelf.Value = 0;
			_rack.Enabled = enable;
			_rack.Value = 0;
			_box.Enabled = enable;
			_box.Value = 0;

			_note.Enabled = enable;
			_note.Text = "";
			_disposition.Enabled = enable;
			_disposition.Text = "";

			_outDate.IsNullDate = true;
			_outDate.Enabled = enable;

			_chkIncludeComment.Enabled = enable;
			_chkIncludeComment.Checked = false;
			_chkIncludeDisposition.Enabled = enable;
			_chkIncludeDisposition.Checked = false;
		}
		#endregion initialize

		public override void New()
		{
			base.New();
			this._editType.Text = "0";
		}

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnRetrieveItems")
				SelectSamples();
			if (sender.Name == "btnUpdateSelected")
				UpdateSelected();
			if (sender.Name == "btnUpdateAll")
				UpdateAll();
			if (sender.Name == "btnRemoveBatch")
				RemoveBatch();
			if (sender.Name == "btnClear")
				ClearInfo();
			if (sender.Name == "btnPrint")
				DoPrint();

			if (_testSamples.RowCount == 0)
				this._btnPrint.Enabled = false;
			else
				this._btnPrint.Enabled = true;
		}

		#region select samples
		private void SelectSamples()
		{
			SampleChooser4Dlg dlc = new SampleChooser4Dlg();
			dlc.Owner = this._form;
			dlc.Text = "Select Samples";
			dlc.SelectSampleClick += new ctsu.Admin.Forms.CoreLab.SampleChooser4Dlg.SelectSampleButtonClickEventHandler(dlc_SelectSampleClick);
			dlc.Show();
		}

		private void dlc_SelectSampleClick(object sender, SelectSamplesEventArgs e)
		{
			if (e.SelectType == 0)
				RetrieveSampleBatch(e.ID);
			else if (e.SelectType == 1)
				RetrieveOneSample(e.ID, true);
			else
				RetrieveBox(e.Location);


			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;
			if (grid.RowCount > 0)
			{
				if (!_btnUpdateSelected.Enabled)
				{
					_btnUpdateSelected.Enabled = true;
					_btnUpdateAll.Enabled = true;
					_btnRemoveBatch.Enabled = true;
					_btnPrint.Enabled = true;
				}
			}
		}

		private void RetrieveOneSample(int id, bool displayMessage)
		{
			StringBuilder sb = new StringBuilder();

			if (IsInList(id))
			{
				if (displayMessage)
				{
					sb.Append("SST ID: " + id + " is already in the list");
					MessageBox.Show(this._form, sb.ToString(), "Duplicate ID",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				return;
			}

			string sql = "SELECT s.ID, s.PatientName, s.Protocol, " +
				" st.Display, s.Location, s.OutDate, s.Disposition, s.Notes " +
				" FROM Sst s LEFT JOIN SampleType_L st" +
				" ON s.SampleType = st.ID " +
				" WHERE s.ID =" + id;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Sample samp = null;
				string message = "";

				grid.BeginUpdate();
				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					samp = new Sample();
					samp.TestID = reader.GetInt32(0);
					samp.Protocol = reader.GetInt32(2);
					//get protocolInfo
					samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

					samp.PatientName = reader.GetString(1);
					//get the patient info
					samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);

					if (!reader.IsDBNull(3))
						samp.SampleName = reader.GetString(3);
					if (!reader.IsDBNull(4))
						samp.Location = reader.GetString(4);
					if (!reader.IsDBNull(5))
						samp.OutDate = reader.GetDateTime(5);
					if (!reader.IsDBNull(6))
						samp.Disposition = reader.GetString(6);
					if (!reader.IsDBNull(7))
						samp.Note = reader.GetString(7);
					fgbl.AddRow(samp, 0);
				}
				else
				{
					sb.Append("SST ID: " + id + " could not be found");
					MessageBox.Show(this._form, sb.ToString(), "SST Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
					reader.Close();
					return;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sst sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get SST Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private void RetrieveSampleBatch(int num)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT s.ID, s.PatientName, s.Protocol, " +
				" st.Display, s.Location, s.OutDate, s.Disposition, s.Notes " +
				" FROM Sst s LEFT JOIN SampleType_L st" +
				" ON s.SampleType = st.ID " +
				" WHERE s.BatchNum =" + num +
				" ORDER BY s.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{

				reader = DataAccess.GetDataReader(sql);
				Sample samp = null;
				string message = "";

				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					grid.BeginUpdate();
					do
					{
						samp = new Sample();
						samp.TestID = reader.GetInt32(0);
						if (IsInList(samp.TestID))
							continue;
						samp.Protocol = reader.GetInt32(2);
						//get protocolInfo
						samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

						samp.PatientName = reader.GetString(1);

						if (!reader.IsDBNull(3))
							samp.SampleName = reader.GetString(3);
						if (!reader.IsDBNull(4))
							samp.Location = reader.GetString(4);
						if (!reader.IsDBNull(5))
							samp.OutDate = reader.GetDateTime(5);
						if (!reader.IsDBNull(6))
							samp.Disposition = reader.GetString(6);
						if (!reader.IsDBNull(7))
							samp.Note = reader.GetString(7);
						fgbl.AddRow(samp, 0);
					}
					while (reader.Read());
				}
				else
				{
					sb.Append("Batch was not found.");
					MessageBox.Show(this._form, sb.ToString(), "Batch Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve batch!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Batch Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private void RetrieveBox(string location)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT s.ID, s.PatientName, s.Protocol, " +
				" st.Display, s.Location, s.OutDate, s.Disposition, s.Notes " +
				" FROM Sst s LEFT JOIN SampleType_L st" +
				" ON s.SampleType = st.ID " +
				" WHERE s.location ='" + location + "'" +
				" ORDER BY s.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{

				reader = DataAccess.GetDataReader(sql);
				Sample samp = null;
				string message = "";

				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					grid.BeginUpdate();
					do
					{
						samp = new Sample();
						samp.TestID = reader.GetInt32(0);
						if (IsInList(samp.TestID))
							continue;

						samp.Protocol = reader.GetInt32(2);
						//get protocolInfo
						samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

						samp.PatientName = reader.GetString(1);

						if (!reader.IsDBNull(3))
							samp.SampleName = reader.GetString(3);
						if (!reader.IsDBNull(4))
							samp.Location = reader.GetString(4);
						if (!reader.IsDBNull(5))
							samp.OutDate = reader.GetDateTime(5);
						if (!reader.IsDBNull(6))
							samp.Disposition = reader.GetString(6);
						if (!reader.IsDBNull(7))
							samp.Note = reader.GetString(7);

						fgbl.AddRow(samp, 0);
					}
					while (reader.Read());
				}
				else
				{
					sb.Append("Location was not found.");
					MessageBox.Show(this._form, sb.ToString(), "Location Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve location!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Location Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private bool IsInList(int id)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridStyleInfo gsi = null;

			if (grid.RowCount == 0)
				return false;

			for (int i = 1; i <= grid.RowCount; i++)
			{
				gsi = grid[i, 1];
				if (gsi.Text.Length > 0)
					if (Convert.ToInt32(gsi.CellValue) == id)
						return true;
			}
			return false;
		}
		#endregion select samples

		#region get display data
		private void ClearInfo()
		{
			ClearLocation();
			this._outDate.IsNullDate = true;
			this._note.Text = "";
			this._disposition.Text = "";
			this._chkIncludeComment.Checked = false;
			this._chkIncludeDisposition.Checked = false;
		}
		private void ClearLocation()
		{
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			this._shelf.Value = 0;
			this._rack.Value = 0;
			this._box.Value = 0;

			if (ignoreEvent)
				ignoreEvent = false;
		}
		protected override void grd_CellDoubleClick(object sender, GridCellClickEventArgs e)
		{
			if (e.RowIndex < 1)
				return;
			if (this.FormMode == EditMode.Edit || this.FormMode == EditMode.New)
				FillControlsWithRowData(e.RowIndex);
		}

		private void FillControlsWithRowData(int row)
		{
			GridControl grid = ((BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"]).Grid;
			//location			
			string sVal = grid[row, 5].Text;
			DisplayLocationInControls(sVal);

			if (grid[row, 6].Text.Length == 0)
				this._outDate.IsNullDate = true;
			else
				this._outDate.Value = DateTime.Parse(grid[row, 6].Text);

			this._disposition.Text = grid[row, 7].Text;
			this._note.Text = grid[row, 8].Text;
		}

		private void DisplayLocationInControls(string location)
		{
			if (location.Length == 0)
			{
				ClearLocation();
				return;
			}

			string[] a = location.Split(',');
			foreach (string s in a)
			{
				if (s.StartsWith("Fz"))
				{
					this._freezer.SelectedValue = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Sf"))
				{
					this._shelf.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Rk"))
				{
					this._rack.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Bx"))
				{
					this._box.Value = Convert.ToInt32(s.Substring(3));
				}
			}
		}

		#endregion get display data

		#region search
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;
			ctl.Enabled = false;

			SearchSamples spd = new SearchSamples();
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				base.Search(sender);
			else if (spd.SearchChoice == 1)
				SelectByLabel();

			ctl.Enabled = true;
		}

		private void SelectByLabel()
		{

			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this.FormInfo.SearchFormInfo["SstEditBatchSamples"];
			if (si == null)
			{
				MessageBox.Show("Search criteria is not defined.", "Search Criteria Not Fount",
					MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			FormSearch fs = new FormSearch();
			//set the title bar
			//fs.Text = si.Name + " Search";

			//get the search fields			
			foreach (ReportColumn rc in si.SearchFields)
				fs.SearchFields.Items.Add(rc);

			//design list view for result fields			
			ListView lvw = fs.SearchResults;
			lvw.Columns.Clear();
			if (lvw != null)
			{
				foreach (ReportColumn rc in si.SearchResultCols)
				{
					ColumnHeader ch = new ColumnHeader();
					ch.Text = rc.DisplayName;
					ch.Width = -2;
					lvw.Columns.Add(ch);
				}
			}

			SearchSamplesController sc = new SearchSamplesController(fs, si);
			fs.Controller = sc;
			fs.Owner = this._form;
			sc.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
			fs.Closing += new CancelEventHandler(fs_Closing);
			IsSearchVisible = true;
			fs.Show();
		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}
		#endregion search

		#region update remove batch
		private void RemoveBatch()
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			ArrayList alRows = new ArrayList();
			int row = 0;
			int top = 0;
			int bottom = 0;
			for (int i = 0; i < list.Count; i++)
			{
				top = list[i].Top;
				bottom = list[i].Bottom;
				if (bottom > top)
					GetSelectedRows(alRows, top, bottom);
				else
					alRows.Add(list[i].Top);
			}
			for (int i = 0; i < alRows.Count; i++)
			{
				row = (int)alRows[i];
				row -= i;
				DataRow dr = (DataRow)fgbl.Grid[row, 0].Tag;
				dr.RejectChanges();
				fgbl.RemoveRow(row);
			}

			if (grid.RowCount == 0)
			{
				_btnRemoveBatch.Enabled = false;
				_btnUpdateSelected.Enabled = false;
				_btnUpdateAll.Enabled = false;
				_btnPrint.Enabled = false;
			}
		}

		private void GetSelectedRows(ArrayList alRows, int top, int bottom)
		{
			int rows = bottom - top + 1;
			for (int i = 0; i < rows; i++)
				alRows.Add(top + i);
		}

		private void UpdateSelected()
		{
			if (!VerifyAddToBatch(0))
				return;

			Sample samp = this.SetReplacementColumns();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			foreach (GridRangeInfo range in list)
			{
				for (int i = range.Top; i <= range.Bottom; i++)
					fgbl.ReplaceRow(samp, i);
			}
		}

		private void UpdateAll()
		{
			if (!VerifyAddToBatch(0))
				return;

			Sample samp = this.SetReplacementColumns();
			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			for (int i = 1; i <= fgbl.Grid.RowCount; i++)
				fgbl.ReplaceRow(samp, i);
		}

		private Sample SetReplacementColumns()
		{
			Sample samp = new Sample();

			if (_outDate.IsNullDate)
			{
				samp.OutDate = CremaConstants.NullDate;
				samp.Location = GetFormatatedLocation();
			}
			else
			{
				samp.OutDate = _outDate.Value;
				samp.Location = "";
			}


			if (this._chkIncludeDisposition.Checked)
				samp.Disposition = this._disposition.Text;
			if (this._chkIncludeComment.Checked)
				samp.Note = this._note.Text;
			return samp;
		}

		private string GetFormatatedLocation()
		{
			if (_freezer.SelectedValue == null)
				return "";

			string location = "Fz:" + this._freezer.SelectedValue.ToString() + "," +
				"Sf:" + this._shelf.Value.ToString() + "," +
				"Rk:" + this._rack.Value.ToString() + "," +
				"Bx:" + this._box.Value.ToString();
			return location;
		}

		private bool VerifyAddToBatch(int type)
		{
			bool bLocation = VerifyLocation();
			if ((_outDate.IsNullDate) && (!bLocation))
			{
				MessageBox.Show(this._form, "You must enter a valid location or out date.", "Invalid Location or Out Date", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return false;
			}

			if ((!_outDate.IsNullDate) && (bLocation))
			{
				MessageBox.Show(this._form, "You cannot enter both location and out date.", "Invalid Location or Out Date", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return false;
			}
			return true;
		}

		private bool VerifyLocation()
		{
			if (this._freezer.SelectedIndex == -1)
				return false;
			if (this._shelf.Value == 0)
				return false;
			if (this._shelf.Value > 9)
				return false;
			if (this._rack.Value > 9)
				return false;
			if (this._box.Value == 0)
				return false;
			return true;
		}
		#endregion add batch

		#region print
		private void DoPrint()
		{
			if (!HasRows())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("There are no labels to print.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Labels", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			if (HasRowNoID())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("You must press save to give the new labels an ID.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Label ID", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			if (_chkPrintReport.Checked)
				PrintReport(0);

		}

		private void PrintReport(int type)
		{
			StringBuilder sb = new StringBuilder();
			string formatFile = System.Windows.Forms.Application.StartupPath + "\\Bartender\\" + CremaConstants.LabelReportFormatFile;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this._form) == DialogResult.Cancel)
				return;

			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			Cursor.Current = Cursors.WaitCursor;

			if (type == 0)
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);

			_sBatch = this._currentPrimaryID.ToString();

			try
			{
				System.Windows.Forms.Application.DoEvents();

				_page = 1;
				_startRow = 1;
				_startRange = 0;

				if (this._chkPrintSelected.Checked)
				{
					if (grid.Selections.Count == 0)
					{
						sb.Append("Select rows to print or uncheck the 'Print Select Rows' check box.");
						MessageBox.Show(this._form, sb.ToString(), "No Rows Selected", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
					else
					{
						//get the start row								
						GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
						GridRangeInfo range = (GridRangeInfo)list[0];
						_startRow = range.Top;
					}
				}
				else
				{
					grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
					doClear = true;
				}

				this._pDoc.Print();
				if (doClear)
					grid.Selections.Clear();
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not start bartender server");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Bartender Server Failed To Start", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				if (type == 0)
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
			}
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{

			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchDate", this._form.Controls)).Value.ToShortDateString();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - SST Change Location Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				sb.Append("   Batch Name: " + this._batchName.Text);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Test Samples Check-in Report - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25; //+75
			float c2 = 100; //+100
			float c3 = 200; //+75			
			float c4 = 275; //150
			float c5 = 425; //150			
			float c6 = 575; //200
			float c7 = 775; //200

			float c1W = 75; //id            
			float c2W = 100; //patient 			
			float c3W = 75;  //protocol
			float c4W = 150; //sample			
			float c5W = 150; //location
			float c6W = 200;  //disposition
			float c7W = 200;  //note

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("SST ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Sample", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Disposition", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Comment", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			//PatientInfo pi = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					if (curLine == maxLines)
					{
						_startRow = row;
						_startRange = i;
						this._page++;
						e.HasMorePages = true;
						return;
					}


					yDraw = yPos + 5;
					//id
					iVal = (int)grid[row, 1].CellValue;

					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
					sVal = grid[row, 2].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//protocol
					PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
					sVal = grid[row, 3].Text;
					gfx.DrawString(sVal.ToString(), prntFont, Brushes.Black, rec);

					//sample
					PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					sVal = grid[row, 4].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//location
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					sVal = grid[row, 5].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					sVal = grid[row, 6].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
					sVal = grid[row, 7].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}

		#endregion print
	}
}
